package com.dd.duu.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dc.base.domain.DPage;
import com.dd.dc.base.domain.DResult;
import com.dd.dc.entity.users.DPermission;
import com.dd.duu.service.PermissionClient;
import com.dd.duu.vo.MenuTreeVo;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 权限/菜单信息表 前端控制器
 * </p>
 *
 * @author JueDream
 * @since 2021-03-05
 */
@Slf4j
@RestController
@RequestMapping("/permission/c/")
@GlobalTransactional(rollbackFor = Exception.class) // 分布式事务seata
public class PermissionController {

    @Autowired
    PermissionClient permissionClient;

    @ApiOperation(value = "根据用户查询菜单接口")
    @PostMapping(value = "/findMenuByUserId")
    public DResult<List<DPermission>> findMenuByUserId(@RequestBody Map<String,Object> map){
        Object userId = Optional.ofNullable(map.get("userId")).orElse(0);
        List<DPermission> permissions = permissionClient.findPermissionByUserId(Integer.parseInt(userId.toString()));
        return DResult.of(permissions);
    }

    @ApiOperation(value = "根据用户查询菜单接口-返回对比")
    @PostMapping(value = "/findUserMenuByUserId")
    public DResult<MenuTreeVo> findUserMenuByUserId(@RequestBody Map<String,Object> map){
        Object userId = Optional.ofNullable(map.get("userId")).orElse(Integer.MAX_VALUE);
        List<DPermission> permissionAll = permissionClient.findPermissionByUserId(0);
        List<DPermission> permissionHave = permissionClient.findPermissionByUserId(Integer.parseInt(userId.toString()));
        MenuTreeVo menuTreeVo = MenuTreeVo.builder().permissionAll(permissionAll).permissionHave(permissionHave).build();
        return DResult.of(menuTreeVo);
    }

    @ApiOperation(value = "根据角色查询菜单接口")
    @PostMapping(value = "/findMenuByRoleId")
    public DResult<MenuTreeVo> findMenuByRoleId(@RequestBody Map<String,Object> map){
        String roleIdStr = map.get("roleIdList").toString();
        // 用户ID
        Object userId = Optional.ofNullable(map.get("userId")).orElse(Integer.MAX_VALUE);
        List<DPermission> permissionHave = new ArrayList<>();
        if (StrUtil.isNotBlank(roleIdStr)){
            permissionHave = permissionClient.findPermissionByUserId(Integer.parseInt(userId.toString()));
        }else{
            roleIdStr = "0";
        }
        // 角色Ids
        List<Integer> roleIds = Arrays.asList(roleIdStr.split(",")).stream().map(r -> Integer.parseInt(r.trim())).collect(Collectors.toList());
        List<DPermission> permissionAll = permissionClient.findPermissionByRoleId(roleIds);
        MenuTreeVo menuTreeVo = MenuTreeVo.builder().permissionAll(permissionAll).permissionHave(permissionHave).build();
        return DResult.of(menuTreeVo);
    }

    @ApiOperation(value = "根据角色ID查询菜单接口")
    @PostMapping(value = "/findUserMenuByRoleId")
    public DResult<MenuTreeVo> findUserMenuByRoleId(@RequestParam Integer roleId){
        List<Integer> roleIds = new ArrayList<>();
        roleIds.add(roleId);
        List<DPermission> permissionHave = permissionClient.findPermissionByRoleId(roleIds);
        List<Integer> roleIdAlls = new ArrayList<>();
        roleIdAlls.add(1);
        List<DPermission> permissionAll = permissionClient.findPermissionByRoleId(roleIdAlls);
        MenuTreeVo menuTreeVo = MenuTreeVo.builder().permissionAll(permissionAll).permissionHave(permissionHave).build();
        return DResult.of(menuTreeVo);
    }

    @ApiOperation(value = "权限分页列表接口")
    @PostMapping("/queryPermissionList")
    public DResult<DPage<DPermission>> queryPermissionList(@RequestParam int page, @RequestParam int limit, @RequestParam String permissionName){
        log.info("UserUI queryPermissionList start ... {}");
        Page<DPermission> pages = permissionClient.queryPermissionList(page, limit, permissionName);
        DPage<DPermission> pPage = DPage.to(pages);
        return DResult.of(pPage);
    }

    @Transactional
    @ApiOperation(value = "权限新增/更新")
    @PostMapping("saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody DPermission permission){
        boolean flag = false;
        // 判断新增/更新
        if (Objects.isNull(permission.getPId())) {
            // 新增权限
            Integer pId = permissionClient.insert(permission);
            if (pId > 0){
                flag = true;
            }
        }else{
            // 更新权限
            flag = permissionClient.updateById(permission);
        }
        return DResult.of(flag);
    }

    @Transactional
    @ApiOperation(value = "权限删除")
    @DeleteMapping("deletePermission")
    public DResult deletePermission(@RequestParam Integer pId){
        boolean flag = permissionClient.delete(pId);
        return DResult.of(flag);
    }

}
